﻿using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Internal;
using Microsoft.Extensions.Options;
using System.Data;
using System.Globalization;
using System.Linq;
using System.Security.Claims;
using System.Xml.Linq;
using 第二课堂评审系统.Models;
using static 第二课堂评审系统.Controllers.AdminController;
using static 第二课堂评审系统.Controllers.PublicController;

namespace 第二课堂评审系统.Controllers
{
    [Route("api/[controller]/[action]")]
    [ApiController]
    [Authorize]
    public class AdminController : ControllerBase
    {
        private readonly _MyDbContext Db;
        private readonly IOptionsSnapshot<JWTSettings> jwtSettingsOpt;
        public AdminController(_MyDbContext db, IOptionsSnapshot<JWTSettings> jwtSettingsOpt)
        {
            Db = db;
            this.jwtSettingsOpt = jwtSettingsOpt;
        }
        public record NewStu(string Sname, int Sno, string Scollege);
        [HttpPut]//单个新增学生
        public ActionResult addStudent([FromBody] NewStu newStu)
        {
            try
            {
                User user = new User();
                user.Name = newStu.Sname;
                user.StuNum = newStu.Sno;
                user.college = newStu.Scollege;
                user.passWord = MD5Algorithm.ChangeToMD5("123456");
                Role role = new Role();
                role.Name = "S0";
                user.Roles = new List<Role> { role };
                role.Users = user;
                Db.Roles.Add(role);
                Db.Users.Add(user);
                Db.SaveChanges();
            }
            catch (Exception ex)
            {
                return BadRequest("添加失败");
            }
            return Ok("添加成功");
        }

        public record NewStuS(string Sname, int Sno, string Scollege);
        [HttpPut]//批量添加学生
        public ActionResult addStudents([FromBody] NewStuS[] newStuS)
        {
            try
            {

                foreach (var stu in newStuS)
                {
                    Role role = new Role();
                    role.Name = "S0";
                    User user = new User { Name = stu.Sname, StuNum = stu.Sno, college = stu.Scollege, passWord = MD5Algorithm.ChangeToMD5("123456") };
                    user.Roles = new List<Role> { role };
                    role.Users = user;
                    Db.Roles.Add(role);
                    Db.Users.Add(user);
                }
                Db.SaveChanges();
            }
            catch { return BadRequest("批量添加出错，请检查格式"); }
            return Ok("添加成功");
        }

        public record NewTea(string Sname, int Sno, string Scollege);
        [HttpPut]//单个添加教师
        public ActionResult addTeacher([FromBody] NewTea newTea)
        {
            try
            {
                User user = new User();
                user.Name = newTea.Sname;
                user.StuNum = newTea.Sno;
                user.college = newTea.Scollege;
                user.passWord = MD5Algorithm.ChangeToMD5("123456");
                Role role = new Role();
                role.Name = "T0";
                user.Roles = new List<Role> { role };
                role.Users = user;

                Db.Roles.Add(role);
                Db.Users.Add(user);
                Db.SaveChanges();
            }
            catch (Exception ex)
            {
                return BadRequest("添加失败");
            }
            return Ok("添加成功");
        }

        [HttpPut]//批量添加教师
        public ActionResult addTeachers([FromBody] NewTea[] newTeas)
        {
            try
            {
                foreach (var tea in newTeas)
                {
                    User user = new User();
                    user.Name = tea.Sname;
                    user.StuNum = tea.Sno;
                    user.college = tea.Scollege;
                    user.passWord = MD5Algorithm.ChangeToMD5("123456");
                    Role role = new Role();
                    role.Name = "T0";
                    user.Roles = new List<Role> { role };
                    role.Users = user;

                    Db.Roles.Add(role);
                    Db.Users.Add(user);
                }
                Db.SaveChanges();
            }
            catch { return BadRequest("批量添加失败，请检查格式"); }
            return Ok("导入成功");
        }

        [HttpDelete]//删除学生
        public ActionResult deleteUser(int Sno)
        {

            //User? user = Db.Users.Where(u => u.StuNum == Sno).Include(u=>u.partnar).ThenInclude(p=>p.members).Include(u=>u.Roles)!.Include(u=>u.achievements).Include(u=>u.allPartnar).Include(u=>u.notices).ToList().SingleOrDefault()!;
            //User? user1 = user;
            User? user = Db.Users.Where(u => u.StuNum == Sno).ToList().SingleOrDefault();
            user!.isDeleted = true;

            //if (user.Roles != null)//角色中移除
            //{
            //    Role role = user.Roles[0];
            //    user.Roles[0].Users = null;
            //    user.Roles.Remove(user.Roles[0]);
            //    Db.Roles.Remove(role);

            //    Console.WriteLine("删除角色中");
            //}

            //Db.Users.Remove(user);
            //if (user1.partnar!=null)
            //{
            //    user1.partnar.members!.Remove(user1);//小组中移除

            //    Console.WriteLine("小组移除");
            //}


            Db.SaveChanges();
            return Ok("删除成功");
        }

        [HttpPut]//重置密码
        public ActionResult rePassword(int Sno)
        {
            User? user = Db.Users.Where(u => u.StuNum == Sno).ToList().SingleOrDefault()!;
            user.passWord = MD5Algorithm.ChangeToMD5("123456");//重置密码
            Db.SaveChanges();
            return Ok("密码重置成功");
        }

        [HttpGet]//获取所有学生
        public ActionResult getAllStudents()
        {
            var AllUser = Db.Users.Include(u => u.Roles).ToList()!;
            var needUser = AllUser.Where(u => u.Roles![0].Name == "S0" || u.Roles![0].Name == "S1");
            var js = needUser.Select(o => new { sno = o.StuNum, sname = o.Name, sphone = o.telPhone, scollege = o.college, role = o.Roles![0].Name });

            return new JsonResult(js);


        }


        [HttpGet]//获取所有老师
        public ActionResult getAllTeachers()
        {
            var AllUser = Db.Users.Include(u => u.Roles).ToList()!;
            var needUser = AllUser.Where(u => u.Roles![0].Name == "T0" || u.Roles![0].Name == "T1");
            var js = needUser.Select(o => new { sno = o.StuNum, sname = o.Name, sphone = o.telPhone, scollege = o.college, role = o.Roles![0].Name });

            return new JsonResult(js);
        }



        #region 获取老师们
        [HttpGet]
        public ActionResult getTeachers()
        {
            var AllUser = Db.Users.Include(u => u.Roles).ToList()!;
            //获取指导老师
            var leaderTeachers = AllUser.Where(u => u.Roles![0].Name == "T0");
            var js1 = leaderTeachers.Select(o => new { sno = o.StuNum, label = o.Name });
            //获取评委老师
            var judgeTeachers = AllUser.Where(u => u.Roles![0].Name == "T1");
            var js2 = judgeTeachers.Select(o => new { sno = o.StuNum, label = o.Name });
            var js = new
            {
                leaderTeachers = js1,
                judgeTeachers = js2,
            };
            return new JsonResult(js);
        }
        #endregion



        #region 成为指导老师
        [HttpPut]
        public ActionResult becomeLeader([FromBody] List<int> Teachers)
        {
            using _MyDbContext Context = new _MyDbContext();
            if (Teachers.Count > 0)
            {
                //遍历每个参数
                foreach (int Teacher in Teachers)
                {
                    User user = Context.Users.Include(u => u.Roles).Where(u => u.StuNum == Teacher).FirstOrDefault()!;
                    if (user != null)
                    {
                        //将角色改为指导老师
                        user.Roles![0].Name = "T0";
                    }
                }
            }
            Context.SaveChanges();
            return Ok();
        }
        #endregion



        #region 成为评委老师
        [HttpPut]
        public ActionResult becomeJudge([FromBody] List<int> Teachers)
        {
            using _MyDbContext Context = new _MyDbContext();
            if (Teachers.Count > 0)
            {
                //遍历每个参数
                foreach (int Teacher in Teachers)
                {
                    User user = Context.Users.Include(u => u.Roles).Where(u => u.StuNum == Teacher).FirstOrDefault()!;
                    if (user != null)
                    {
                        //将角色改为评委老师
                        user.Roles![0].Name = "T1";
                    }
                }
            }
            Context.SaveChanges();
            return Ok();
        }
        #endregion



        #region 获得所有分配了的评委老师
        [HttpGet]
        public ActionResult getAllyesType()
        {
            using _MyDbContext Context = new _MyDbContext();
            List<User> users = Context.Users.Include(u => u.Roles).Where(u => u.track != null && u.track != "").ToList();
            users = users.Where(u => u.Roles == null ? false : u.Roles[0].Name == "T1").ToList();
            var yyxtkfData = new List<object>();              //应用系统开发
            var webxtkfData = new List<object>();           //Web系统开发
            var yxkfData = new List<object>();              //游戏开发
            var jhsjykfData = new List<object>();           //交互设计与开发
            var sjwjyfxData = new List<object>();           //数据挖掘与分析
            if (users != null)
                foreach (var user in users)
                {
                    if (user.track == "应用系统开发")
                    {
                        yyxtkfData.Add(new { sno = user.StuNum, label = user.Name });
                    }
                    else if (user.track == "Web系统开发")
                    {
                        webxtkfData.Add(new { sno = user.StuNum, label = user.Name });
                    }
                    else if (user.track == "游戏开发")
                    {
                        yxkfData.Add(new { sno = user.StuNum, label = user.Name });
                    }
                    else if (user.track == "交互设计与开发")
                    {
                        jhsjykfData.Add(new { sno = user.StuNum, label = user.Name });
                    }
                    else if (user.track == "数据挖掘与分析")
                    {
                        sjwjyfxData.Add(new { sno = user.StuNum, label = user.Name });
                    }
                }
            var js = new { yyxtkfData, webxtkfData, yxkfData, jhsjykfData, sjwjyfxData };
            return new JsonResult(js);
        }
        #endregion



        #region 获得所有未分配的评委老师
        [HttpGet]
        public ActionResult getAllnoType()
        {
            using _MyDbContext Context = new _MyDbContext();
            List<User> users = Context.Users.Include(u => u.Roles).Where(u => u.track == null || u.track == "").ToList();
            users = users.Where(u => u.Roles == null ? false : u.Roles[0].Name == "T1").ToList();
            var js = users.Select(u => new { sno = u.StuNum, label = u.Name }).ToList();
            return new JsonResult(js);
        }
        #endregion



        #region 从评委老师中为老师分配比赛类型
        public record Argument(string type, List<int> teachersArr);
        [HttpPut]
        public ActionResult AssignTeahcerType([FromBody] Argument argument)
        {
            using _MyDbContext Context = new _MyDbContext();
            if (argument.teachersArr != null)
            {
                foreach (int teacher in argument.teachersArr)
                {
                    User user = Context.Users.Include(u => u.Roles).Where(o => o.StuNum == teacher).FirstOrDefault()!;
                    if (user != null && user.Roles[0].Name == "T1")
                    {
                        string typeName = "";
                        if (argument.type == "yyxtkf") { typeName = "应用系统开发"; }
                        else if (argument.type == "webxtkf") { typeName = "Web系统开发"; }
                        else if (argument.type == "yxkf") { typeName = "游戏开发"; }
                        else if (argument.type == "jhsjykf") { typeName = "交互设计与开发"; }
                        else if (argument.type == "sjwjyfx") { typeName = "数据挖掘与分析"; }
                        else { return BadRequest("该类型不存在"); }
                        user.track = typeName;
                    }  
                    
                }
                Context.SaveChanges();
            }
            else
            {
                return BadRequest("分配失败，请选择老师");
            }
            
            return Ok();
        }
        #endregion


        [HttpGet]//获取分配好的赛道信息
        public ActionResult o_getAllprograms()
        {
            //应用系统开发,Web系统开发,游戏开发,交互设计与开发,数据挖掘与分析
            var ParInfo = Db.Partnars.Include(p => p.MyPreliminary).Include(p => p.project).ToList();
            var TeaInfo = Db.Users.Include(u => u.JudgePre).Include(u => u.Roles).ToList();
            var JudInfo = TeaInfo.Where(u => u.Roles![0].Name == "T1").ToList();

            var yyxtkfStu = ParInfo.Where(p => p.searchDirection == "应用系统开发").ToList();
            var webxtkfStu = ParInfo.Where(p => p.searchDirection == "Web系统开发").ToList();
            var yxkfStu = ParInfo.Where(p => p.searchDirection == "游戏开发").ToList();
            var jhsjykfStu = ParInfo.Where(p => p.searchDirection == "交互设计与开发").ToList();
            var sjwjyfxStu = ParInfo.Where(p => p.searchDirection == "数据挖掘与分析").ToList();

            var yyxtkfTea = JudInfo.Where(p => p.track == "应用系统开发").ToList();
            var webxtkfTea = JudInfo.Where(p => p.track == "Web系统开发").ToList();
            var yxkfTea = JudInfo.Where(p => p.track == "游戏开发").ToList();
            var jhsjykfTea = JudInfo.Where(p => p.track == "交互设计与开发").ToList();
            var sjwjyfxTea = JudInfo.Where(p => p.track == "数据挖掘与分析").ToList();

            var js = new
            {
                yyxtkfData = new
                {
                    itemData = yyxtkfStu.Select(t => new { itemId = t.project!.Id, itemName = t.project.Name, roomId = t.MyPreliminary == null ? null : t.MyPreliminary!.classRoom }),
                    teacherData = yyxtkfTea.Select(t => new { sno = t.StuNum, sname = t.Name, roomId = t.JudgePre == null ? null : t.JudgePre.classRoom })
                },
                webxtkfData = new
                {
                    itemData = webxtkfStu.Select(t => new { itemId = t.project!.Id, itemName = t.project.Name, roomId = t.MyPreliminary == null ? null : t.MyPreliminary!.classRoom }),
                    teacherData = webxtkfTea.Select(t => new { sno = t.StuNum, sname = t.Name, roomId = t.JudgePre == null ? null : t.JudgePre.classRoom })
                },
                yxkfData = new
                {
                    itemData = yxkfStu.Select(t => new { itemId = t.project!.Id, itemName = t.project.Name, roomId = t.MyPreliminary == null ? null : t.MyPreliminary!.classRoom }),
                    teacherData = yxkfTea.Select(t => new { sno = t.StuNum, sname = t.Name, roomId = t.JudgePre == null ? null : t.JudgePre.classRoom })
                },
                jhsjykfData = new
                {
                    itemData = jhsjykfStu.Select(t => new { itemId = t.project!.Id, itemName = t.project.Name, roomId = t.MyPreliminary == null ? null : t.MyPreliminary!.classRoom }),
                    teacherData = jhsjykfTea.Select(t => new { sno = t.StuNum, sname = t.Name, roomId = t.JudgePre == null ? null : t.JudgePre.classRoom })
                },
                sjwjyfxData = new
                {
                    itemData = sjwjyfxStu.Select(t => new { itemId = t.project!.Id, itemName = t.project.Name, roomId = t.MyPreliminary == null ? null : t.MyPreliminary!.classRoom }),
                    teacherData = sjwjyfxTea.Select(t => new { sno = t.StuNum, sname = t.Name, roomId = t.JudgePre == null ? null : t.JudgePre.classRoom })
                },
            };
            return new JsonResult(js);
        }

        public record TTime(string auditStartTime, string auditEndTime);
        [HttpPost]//保存审核时间
        public ActionResult keepAuditTime([FromBody] TTime compTime)
        {
            if (Db.ControllActionTimes.Where(c => c.Name == "审核时间").ToList().SingleOrDefault() == null)
            {
                ControllActionTime controllActionTime = new ControllActionTime();
                controllActionTime.BeginTime = DateTime.ParseExact(compTime.auditStartTime, "yyyy-MM-dd HH:mm:ss", CultureInfo.InvariantCulture);
                controllActionTime.EndTime = DateTime.ParseExact(compTime.auditEndTime, "yyyy-MM-dd HH:mm:ss", CultureInfo.InvariantCulture);
                controllActionTime.Name = "审核时间";
                Db.ControllActionTimes.Add(controllActionTime);
            }
            else
            {
                ControllActionTime controllActionTime = Db.ControllActionTimes.Where(c => c.Name == "审核时间").ToList().Single();
                controllActionTime.BeginTime = DateTime.ParseExact(compTime.auditStartTime, "yyyy-MM-dd HH:mm:ss", CultureInfo.InvariantCulture);
                controllActionTime.EndTime = DateTime.ParseExact(compTime.auditEndTime, "yyyy-MM-dd HH:mm:ss", CultureInfo.InvariantCulture);
            }

            Db.SaveChanges();
            return Ok();
        }

        public record OTime(string originStartTime, string originEndTime);
        [HttpPost]//初赛时间
        public ActionResult keepOriginTime([FromBody] OTime compTime)
        {
            if (Db.ControllActionTimes.Where(c => c.Name == "初赛时间").ToList().SingleOrDefault() == null)
            {
                ControllActionTime controllActionTime = new ControllActionTime();
                controllActionTime.BeginTime = DateTime.ParseExact(compTime.originStartTime, "yyyy-MM-dd HH:mm:ss", CultureInfo.InvariantCulture);
                controllActionTime.EndTime = DateTime.ParseExact(compTime.originEndTime, "yyyy-MM-dd HH:mm:ss", CultureInfo.InvariantCulture);
                controllActionTime.Name = "初赛时间";
                Db.ControllActionTimes.Add(controllActionTime);
            }
            else
            {
                ControllActionTime controllActionTime = Db.ControllActionTimes.Where(c => c.Name == "初赛时间").ToList().Single();
                controllActionTime.BeginTime = DateTime.ParseExact(compTime.originStartTime, "yyyy-MM-dd HH:mm:ss", CultureInfo.InvariantCulture);
                controllActionTime.EndTime = DateTime.ParseExact(compTime.originEndTime, "yyyy-MM-dd HH:mm:ss", CultureInfo.InvariantCulture);
            }

            Db.SaveChanges();
            return Ok();
        }

        public record FTime(string finalStartTime, string finalEndTime);
        [HttpPost]//决赛时间
        public ActionResult keepFinalTime([FromBody] FTime compTime)
        {
            if (Db.ControllActionTimes.Where(c => c.Name == "决赛时间").ToList().SingleOrDefault() == null)
            {
                ControllActionTime controllActionTime = new ControllActionTime();
                controllActionTime.BeginTime = DateTime.ParseExact(compTime.finalStartTime, "yyyy-MM-dd HH:mm:ss", CultureInfo.InvariantCulture);
                controllActionTime.EndTime = DateTime.ParseExact(compTime.finalEndTime, "yyyy-MM-dd HH:mm:ss", CultureInfo.InvariantCulture);
                controllActionTime.Name = "决赛时间";
                Db.ControllActionTimes.Add(controllActionTime);
            }
            else
            {
                ControllActionTime newAT = Db.ControllActionTimes.Where(c => c.Name == "决赛时间").ToList().Single();
                newAT.BeginTime = DateTime.ParseExact(compTime.finalStartTime, "yyyy-MM-dd HH:mm:ss", CultureInfo.InvariantCulture);
                newAT.EndTime = DateTime.ParseExact(compTime.finalEndTime, "yyyy-MM-dd HH:mm:ss", CultureInfo.InvariantCulture);
            }
            Db.SaveChanges();
            return Ok();
        }



        #region 决赛分配名额
        [HttpPut]
        public ActionResult AssignIntoFinal(List<string>? itemIdArr)
        {
            using _MyDbContext context = new _MyDbContext();
            if (itemIdArr != null && itemIdArr.Count > 0)
            {
                foreach (string item in itemIdArr)
                {
                    Project project = context.Projects.Include(p => p.Partnar).Where(p => p.Id.ToString() == item).FirstOrDefault();
                    project.projectState = 5;
                }
                context.SaveChanges();
            }
            else
            {
                return BadRequest("项目参数对应项目没有找到");
            }
            return Ok();
        }
        #endregion


        #region 绑定教室
        public record bindRoomArgument(string type, List<string> itemArr, List<int> teacherArr, string roomId, string stage);
        [HttpPut]
        public ActionResult bindRoom([FromBody] bindRoomArgument argument)
        {
            using _MyDbContext Context = new _MyDbContext();
            string typeName = "";
            if (argument.type == "yyxtkf") { typeName = "应用系统开发"; }
            else if (argument.type == "webxtkf") { typeName = "Web系统开发"; }
            else if (argument.type == "yxkf") { typeName = "游戏开发"; }
            else if (argument.type == "jhsjykf") { typeName = "交互设计与开发"; }
            else if (argument.type == "sjwjyfx") { typeName = "数据挖掘与分析"; }
            else { return BadRequest("该类型不存在"); }


            //获取所有项目
            List<Project> allProject = Context.Projects.Include(p => p.Partnar).ToList();

            List<Partnar> listPartnars = new List<Partnar>();
            List<User> judgesList = new List<User>();

            //绑定小组
            if (argument.itemArr != null && argument.itemArr.Count > 0)
            {
                foreach (string item in argument.itemArr)
                {
                    //获取当前项目号的小组
                    Project project = allProject.Where(p => p.Id == Convert.ToInt32(item)).FirstOrDefault()!;
                    if (project == null)
                    {
                        return BadRequest("操作失败，项目号为：" + item + " 的项目不存在");
                    }
                    if (project.Partnar == null)
                    {
                        return BadRequest("操作失败，项目号为：" + item + " 的项目的小组不存在");
                    }
                    Partnar partnar = project.Partnar;

                    //分配项目进度
                    if (argument.stage == "origin")
                        project.projectState = 4;
                    else
                        project.projectState = 5;
                    //添加当前项目号的小组

                    listPartnars.Add(partnar);
                }
            }

            //绑定评委
            if (argument.teacherArr != null && argument.teacherArr.Count > 0)
            {
                foreach (int item in argument.teacherArr)
                {
                    //获取当前工号号的评委
                    User teacher = Context.Users.Where(u => u.StuNum == item).FirstOrDefault()!;
                    teacher.track = typeName;
                    if (teacher == null)
                    {
                        return BadRequest("操作失败，工号为：" + item + " 的教师不存在");
                    }
                    //绑定评委
                    judgesList.Add(teacher);
                }
            }

            //创建初赛表
            if (argument.stage == "origin")
            {
                Preliminary preliminary = new Preliminary();
                preliminary.JoinPartnars = listPartnars;
                preliminary.judgesList = judgesList;

                preliminary.Name = typeName;
                //绑定教室
                preliminary.classRoom = argument.roomId;

                Context.Preliminaries.Add(preliminary);
            }
            //创建决赛表
            else
            {
                Final final = new Final();
                final.JoinPartnars = listPartnars;
                final.judgesList = judgesList;

                final.Name = typeName;
                //绑定教室
                final.classRoom = argument.roomId;

                Context.Finals.Add(final);
            }
            //保存修改
            Context.SaveChanges();
            return Ok();
        }
        #endregion

        [HttpGet]//获取初赛的所有成绩结果
        public IActionResult getOriginScores()
        {
            //查出所有初赛项目
            List<Partnar> ParInfo = Db.Partnars.Include(p => p.project).Include(p => p.achievements).Include(p => p.guideTeacher).Where(p => p.project!.projectState == 4 && p.achievements != null).ToList();

            var yyxtkfStu = ParInfo.Where(p => p.searchDirection == "应用系统开发").ToList();
            var webxtkfStu = ParInfo.Where(p => p.searchDirection == "Web系统开发").ToList();
            var yxkfStu = ParInfo.Where(p => p.searchDirection == "游戏开发").ToList();
            var jhsjykfStu = ParInfo.Where(p => p.searchDirection == "交互设计与开发").ToList();
            var sjwjyfxStu = ParInfo.Where(p => p.searchDirection == "数据挖掘与分析").ToList();

            var js = new
            {
                yyxtkfData =
                    yyxtkfStu.Select(t => new { itemId = t.project!.Id, itemName = t.project.Name, leaderTeacher = t.guideTeacher!.Name, allScores = t.achievements.Where(t => t.Session == 0).ToList().Count == 0 ? 0 : t.achievements!.Where(t => t.Session == 0).Average(t => t.total) , rank = t.project.Rank }),
                webxtkfData =
                    webxtkfStu.Select(t => new { itemId = t.project!.Id, itemName = t.project.Name, leaderTeacher = t.guideTeacher!.Name, allScores = t.achievements.Where(t => t.Session == 0).ToList().Count == 0 ? 0 : t.achievements!.Where(t => t.Session == 0).Average(t => t.total) ,rank=t.project.Rank}),
                yxkfData =
                    yxkfStu.Select(t => new { itemId = t.project!.Id, itemName = t.project.Name, leaderTeacher = t.guideTeacher!.Name, allScores = t.achievements.Where(t => t.Session == 0).ToList().Count == 0 ? 0 : t.achievements!.Where(t => t.Session == 0).Average(t => t.total) ,rank=t.project.Rank}),
                jhsjykfData =
                    jhsjykfStu.Select(t => new { itemId = t.project!.Id, itemName = t.project.Name, leaderTeacher = t.guideTeacher!.Name, allScores = t.achievements.Where(t => t.Session == 0).ToList().Count == 0 ? 0 : t.achievements!.Where(t => t.Session == 0).Average(t => t.total) ,rank=t.project.Rank}),
                sjwjyfxData =
                    sjwjyfxStu.Select(t => new { itemId = t.project!.Id, itemName = t.project.Name, leaderTeacher = t.guideTeacher!.Name, allScores = t.achievements.Where(t => t.Session == 0).ToList().Count == 0 ? 0 : t.achievements!.Where(t => t.Session == 0).Average(t => t.total) ,rank=t.project.Rank}),
            };

            return new JsonResult(js);
        }
        [HttpGet]
        public IActionResult getFinalScores()
        {
            //查出所有初赛项目
            List<Partnar> ParInfo = Db.Partnars.Include(p => p.project).Include(p => p.achievements).Include(p => p.guideTeacher).Where(p => p.project!.projectState == 5 && p.achievements != null).ToList();

            var yyxtkfStu = ParInfo.Where(p => p.searchDirection == "应用系统开发").ToList();
            var webxtkfStu = ParInfo.Where(p => p.searchDirection == "Web系统开发").ToList();
            var yxkfStu = ParInfo.Where(p => p.searchDirection == "游戏开发").ToList();
            var jhsjykfStu = ParInfo.Where(p => p.searchDirection == "交互设计与开发").ToList();
            var sjwjyfxStu = ParInfo.Where(p => p.searchDirection == "数据挖掘与分析").ToList();

            var js = new
            {
                yyxtkfData = yyxtkfStu.Select(t => new { itemId = t.project!.Id, itemName = t.project.Name, leaderTeacher = t.guideTeacher!.Name, allScores = t.achievements.Where(t => t.Session == 1).ToList().Count == 0 ? 0 : t.achievements!.Where(t => t.Session == 1).Average(t => t.total),rank=t.project.Rank }),

                webxtkfData = webxtkfStu.Select(t => new { itemId = t.project!.Id, itemName = t.project.Name, leaderTeacher = t.guideTeacher!.Name, allScores = t.achievements.Where(t => t.Session == 1).ToList().Count == 0 ? 0 : t.achievements!.Where(t => t.Session == 1).Average(t => t.total) , rank = t.project.Rank }),

                yxkfData = yxkfStu.Select(t => new { itemId = t.project!.Id, itemName = t.project.Name, leaderTeacher = t.guideTeacher!.Name, allScores = t.achievements.Where(t => t.Session == 1).ToList().Count == 0 ? 0 : t.achievements!.Where(t => t.Session == 1).Average(t => t.total) ,rank=t.project.Rank}),

                jhsjykfData = jhsjykfStu.Select(t => new { itemId = t.project!.Id, itemName = t.project.Name, leaderTeacher = t.guideTeacher!.Name, allScores = t.achievements.Where(t => t.Session == 1).ToList().Count == 0 ? 0 : t.achievements!.Where(t => t.Session == 1).Average(t => t.total),rank=t.project.Rank }),

                sjwjyfxData = sjwjyfxStu.Select(t => new { itemId = t.project!.Id, itemName = t.project.Name, leaderTeacher = t.guideTeacher!.Name, allScores = t.achievements.Where(t => t.Session == 1).ToList().Count == 0 ? 0 : t.achievements!.Where(t => t.Session == 1).Average(t => t.total),rank=t.project.Rank }),

            };

            return new JsonResult(js);
        }

        [HttpGet]//获取分配好的决赛教室
        public IActionResult f_getAllprograms()
        {
            //应用系统开发,Web系统开发,游戏开发,交互设计与开发,数据挖掘与分析
            var ParInfo = Db.Partnars.Include(p => p.MyFinal).Include(p => p.project).ToList();
            var TeaInfo = Db.Users.Include(u => u.JudgeFin).Include(u => u.Roles).ToList();
            var JudInfo = TeaInfo.Where(u => u.Roles![0].Name == "T1").ToList();

            var yyxtkfStu = ParInfo.Where(p => p.searchDirection == "应用系统开发").ToList();
            var webxtkfStu = ParInfo.Where(p => p.searchDirection == "Web系统开发").ToList();
            var yxkfStu = ParInfo.Where(p => p.searchDirection == "游戏开发").ToList();
            var jhsjykfStu = ParInfo.Where(p => p.searchDirection == "交互设计与开发").ToList();
            var sjwjyfxStu = ParInfo.Where(p => p.searchDirection == "数据挖掘与分析").ToList();

            var yyxtkfTea = JudInfo.Where(p => p.track == "应用系统开发").ToList();
            var webxtkfTea = JudInfo.Where(p => p.track == "Web系统开发").ToList();
            var yxkfTea = JudInfo.Where(p => p.track == "游戏开发").ToList();
            var jhsjykfTea = JudInfo.Where(p => p.track == "交互设计与开发").ToList();
            var sjwjyfxTea = JudInfo.Where(p => p.track == "数据挖掘与分析").ToList();

            var js = new
            {
                yyxtkfData = new
                {
                    itemData = yyxtkfStu.Select(t => new { itemId = t.project!.Id, itemName = t.project.Name, roomId = t.MyFinal == null ? null : t.MyFinal!.classRoom }),
                    teacherData = yyxtkfTea.Select(t => new { sno = t.StuNum, sname = t.Name, roomId = t.JudgeFin == null ? null : t.JudgeFin.classRoom })
                },
                webxtkfData = new
                {
                    itemData = webxtkfStu.Select(t => new { itemId = t.project!.Id, itemName = t.project.Name, roomId = t.MyFinal == null ? null : t.MyFinal!.classRoom }),
                    teacherData = webxtkfTea.Select(t => new { sno = t.StuNum, sname = t.Name, roomId = t.JudgeFin == null ? null : t.JudgeFin.classRoom })
                },
                yxkfData = new
                {
                    itemData = yxkfStu.Select(t => new { itemId = t.project!.Id, itemName = t.project.Name, roomId = t.MyFinal == null ? null : t.MyFinal!.classRoom }),
                    teacherData = yxkfTea.Select(t => new { sno = t.StuNum, sname = t.Name, roomId = t.JudgeFin == null ? null : t.JudgeFin.classRoom })
                },
                jhsjykfData = new
                {
                    itemData = jhsjykfStu.Select(t => new { itemId = t.project!.Id, itemName = t.project.Name, roomId = t.MyFinal == null ? null : t.MyFinal!.classRoom }),
                    teacherData = jhsjykfTea.Select(t => new { sno = t.StuNum, sname = t.Name, roomId = t.JudgeFin == null ? null : t.JudgeFin.classRoom })
                },
                sjwjyfxData = new
                {
                    itemData = sjwjyfxStu.Select(t => new { itemId = t.project!.Id, itemName = t.project.Name, roomId = t.MyFinal == null ? null : t.MyFinal!.classRoom }),
                    teacherData = sjwjyfxTea.Select(t => new { sno = t.StuNum, sname = t.Name, roomId = t.JudgeFin == null ? null : t.JudgeFin.classRoom })
                },
            };
            return new JsonResult(js);
        }

        public record AddRank(int itemId, string rank);
        [HttpPut]//分配奖项
        public IActionResult setRank([FromBody] List<AddRank> rankList)
        {
            List<Project> projects = Db.Projects.Where(p=>p.projectState==5).ToList();
            foreach(var i in rankList)
            {
               Project pr= projects.Where(p => p.Id == i.itemId).FirstOrDefault()!;
                pr.Rank = i.rank;
                pr.projectState = 6;
            }
            Db.SaveChanges();
            return Ok("奖项分配成功");
        }
    }

}

      

